package my.graduation.controller.common;

import my.graduation.enums.HttpCodeEnums;
import my.graduation.result.Result;
import my.graduation.util.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author: RavenLyn
 * @Date: 2024-12-11
 */
@RestController
@RequestMapping
public class OssController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 管理员上传医生
     * @param file
     * @return
     */
    @PostMapping("/admin/upload")
    public Result<String> adminUpload(@RequestPart("file") MultipartFile file) {
        return uploadMethod(file);
    }


    @PostMapping("/doctor/upload")
    public Result<String> doctorUpload(@RequestParam("file")  MultipartFile file) {
        return uploadMethod(file);
    }

    public Result<String> uploadMethod(MultipartFile file){
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
//            System.out.println(objectName);
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(HttpCodeEnums.UPLOAD_FAILED);
        }
    }
}
